from flask import Flask, flash, jsonify, Response, render_template, request, session, redirect, url_for
import simplejson as json
from flask_session import Session
from apps.admin import app, db
from apps.admin.models.book import Book


@app.route("/books", methods=["GET"])
def books():
    if request.headers.get('X-Requested-With') != 'XMLHttpRequest':
        return render_template("book/index.html")
    # bk = Book.query.get(1263)

    page = request.args.get("page", type=int, default=1)  # 获取get请求参数
    limit = request.args.get("limit", type=int, default=10)  # 获取get请求参数
    searchParams = request.args.get("searchParams")  # 获取get请求参数

    title = ""
    if searchParams != None:
        searchParams = json.loads(searchParams)
        title = searchParams.get("title")
    offset = (page - 1) * limit

    Model = Book.query;
    if title != '':
        Model = Model.filter(Book.title == title)

    total = Model.count()
    Model = Model.with_entities(Book.id, Book.rank, Book.title, Book.author, Book.desc, Book.score,
                                Book.createtime).order_by(Book.id.asc()).limit(limit).offset(offset)

    # 打印sql
    stat = Model.statement
    print(stat)

    datas = Model.all()

    data_list = []
    content = {}
    for data in datas:
        # print(data)
        content = {'id': data.id, 'rank': data.rank, 'title': data.title, 'author': data.author, 'desc': data.desc,
                   'score': data.score, 'createtime': data.createtime}
        data_list.append(content)
        content = {}
    result = {'code': 0, "msg": "", "count": total, "data": data_list}
    return Response(json.dumps(result), mimetype='application/json')


@app.route("/book_edit", methods=["GET", "POST"])
def book_edit():
    if request.method == 'GET':
        book_id = request.args.get("id", type=int, default=1)  # 获取get请求参数
        book = Book.query.get(book_id)
        return render_template("book/edit.html", book=book)

    data = request.json
    book_id = data.get("id")
    rank = data.get("rank")
    title = data.get("title")  #
    author = data.get("author")  #
    score = data.get("score")  #
    country = data.get("country")  #
    see_status = data.get("see_status")  #
    link = data.get("link")  #
    desc = data.get("desc")  #

    bookData = {
        "rank": rank,
        "title": title,
        "author": author,
        "score": score,
        "country": country,
        "see_status": see_status,
        "link": link,
        "desc": desc
    }
    # print(bookData)

    book = Book.query.get(book_id)
    book.rank = rank
    book.title = title
    book.author = author
    book.score = score
    book.country = country
    book.see_status = see_status
    book.link = link
    book.desc = desc
    db.session.commit()  # 提交事务

    result = {'code': 1, "msg": "修改成功"}
    return Response(json.dumps(result), mimetype='application/json')


@app.route("/book_add", methods=["GET", "POST"])
def book_add():
    if request.method == 'GET':
        return render_template("book/add.html")

    data = request.json
    book_id = data.get("id")
    rank = data.get("rank")
    title = data.get("title")  #
    author = data.get("author")  #
    score = data.get("score")  #
    country = data.get("country")  #
    see_status = data.get("see_status")  #
    link = data.get("link")  #
    desc = data.get("desc")  #

    book = Book(rank=rank, title=title, author=author, score=score, desc=desc, country=country, see_status=see_status,
                link=link)
    db.session.add(book)
    result = db.session.commit()
    print(result)

    result = {'code': 1, "msg": "提交成功"}
    return Response(json.dumps(result), mimetype='application/json')


@app.route("/book_del", methods=["POST"])
def book_del():
    # user = User.query.filter_by(username='test').first()

    book_id = request.form.get("id")

    book = Book.query.get(book_id)
    db.session.delete(book)
    db.session.commit()

    result = {'code': 1, "msg": "删除成功"}
    return Response(json.dumps(result), mimetype='application/json')
